<template>
  <div class='searchIndex'>
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isSearchResultShow = false"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result
      v-if="isSearchResultShow"
      :search-text="searchText"
    />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 历史记录 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
      @deleteAllSearchHistories="searchHistories = $event"
    />
    <!-- /历史记录 -->
  </div>
</template>

<script>
import searchSuggestion from './components/searchSuggestion'
import searchHistory from './components/searchHistory'
import searchResult from './components/searchResult'
import { setStorage, getStorage } from '@/utils/storage'

export default {
  name: 'searchIndex',
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  props: {},
  data () {
    return {
      searchText: '',
      isSearchResultShow: false, // 是否展示搜索结果
      searchHistories: getStorage('search-histories') || []
    }
  },
  watch: {
    // 监视 searchHistories （历史记录）的修改，如果改变则重新储存
    searchHistories () {
      setStorage('search-histories', this.searchHistories)
    }
  },
  methods: {
    // 根据关键字进行搜索
    onSearch (searchText) {
      this.searchText = searchText
      const index = this.searchHistories.indexOf(this.searchText)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(this.searchText)
      this.isSearchResultShow = true
    }
  }
}
</script>
<style lang='less' scoped></style>
